#include "U2RenderSystemCapabilitiesManager.h"

#include "U2LogManager.h"
#include "U2ArchiveManager.h"
#include "U2Archive.h"
#include "U2StringConverter.h"
#include "U2Exception.h"
#include "U2RenderSystemCapabilitiesSerializer.h"



U2EG_NAMESPACE_USING


//-----------------------------------------------------------------------
template<> U2RenderSystemCapabilitiesManager* U2Singleton<U2RenderSystemCapabilitiesManager>::s_pSingleton = 0;
U2RenderSystemCapabilitiesManager* U2RenderSystemCapabilitiesManager::getSingletonPtr(void)
{
    return s_pSingleton;
}
U2RenderSystemCapabilitiesManager& U2RenderSystemCapabilitiesManager::getSingleton(void)
{
    assert( s_pSingleton );  return ( *s_pSingleton );
}

//-----------------------------------------------------------------------
U2RenderSystemCapabilitiesManager::U2RenderSystemCapabilitiesManager()
: mSerializer(0)
, mScriptPattern("*.rendercaps")
{
    mSerializer = U2_NEW U2RenderSystemCapabilitiesSerializer();
}
//-----------------------------------------------------------------------
U2RenderSystemCapabilitiesManager::~U2RenderSystemCapabilitiesManager()
{
    for (CapabilitiesMap::iterator it = mCapabilitiesMap.begin(), end = mCapabilitiesMap.end(); it != end; it++)
    {
        // free memory in U2RenderSystemCapabilities*
        U2_DELETE it->second;
    }

    U2_DELETE mSerializer;
}

//-----------------------------------------------------------------------
void U2RenderSystemCapabilitiesManager::parseCapabilitiesFromArchive(const U2String& filename, const U2String& archiveType, bool recursive)
{
    // get the list of .rendercaps files
    U2Archive* arch = U2ArchiveManager::getSingleton().load(filename, archiveType);
    U2StringVectorPtr files = arch->find(mScriptPattern, recursive);

    // loop through .rendercaps files and load each one
    for (U2StringVector::iterator it = files->begin(), end = files->end(); it != end; it++)
    {
        U2DataStreamPtr stream = arch->open(*it);
        mSerializer->parseScript(stream);
        stream->close();
    }
}

U2RenderSystemCapabilities* U2RenderSystemCapabilitiesManager::loadParsedCapabilities(const U2String& name)
{
    return mCapabilitiesMap[name];
}

const std::map<U2String, U2RenderSystemCapabilities*> &U2RenderSystemCapabilitiesManager::getCapabilities() const
{
	return mCapabilitiesMap;
}

/** Method used by RenderSystemCapabilitiesSerializer::parseScript */
void U2RenderSystemCapabilitiesManager::_addRenderSystemCapabilities(const U2String& name, U2RenderSystemCapabilities* caps)
{
    mCapabilitiesMap.insert(CapabilitiesMap::value_type(name, caps));
}